{ "cells": [ { "cell_type": "markdown", "id": "33733e0b", "metadata": {}, "source": [ "## Lambda Functions" ] }, { "cell_type": "markdown", "id": "54e5cd79", "metadata": {}, "source": [ "- Anonymous functions" ] }, { "cell_type": "markdown", "id": "91e2ddc0", "metadata": {}, "source": [ "### Find 3x+1" ] }, { "cell_type": "markdown", "id": "6cca3341", "metadata": {}, "source": [ "#### Traditional method" ] }, { "cell_type": "code", "execution_count": 1, "id": "b5d6006b", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "7" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def f(x):\n", " return 3*x+1\n", "\n", "f(2)" ] }, { "cell_type": "markdown", "id": "7bb39838", "metadata": {}, "source": [ "#### Lambda expression" ] }, { "cell_type": "markdown", "id": "111c59b8", "metadata": {}, "source": [ "- Syntax: lambda 0 or more inputs:expression that will be return value\n", "- Can't be used for multiline functions\n", "- Only used if functin can be written in 1 line\n", " - Common applications are sorting and filtering data" ] }, { "cell_type": "markdown", "id": "5dcff8cf", "metadata": {}, "source": [ "- lambda : \"Hello world\"\n", "- lambda x:x\n", "- lambda x,y:x+y\n", "- lambda x,y,z:x+y+z" ] }, { "cell_type": "code", "execution_count": 3, "id": "3c28406c", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "7" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "g=lambda x:3*x+1 # define\n", "g(2) # call" ] }, { "cell_type": "code", "execution_count": 6, "id": "e9aa7dd3", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'sahil s'" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "g=lambda x,y:x.strip()+' '+y.strip()\n", "g('sahil','s')" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.8" } }, "nbformat": 4, "nbformat_minor": 5 }